﻿using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using static light.http.server.httpserver;

namespace server04_websocket
{
    class Program
    {
        static void Main(string[] args)
        {
            var server = new light.http.server.httpserver();
            server.SetFailAction(on404);
            server.SetWebsocketAction("/ws", onWebSocketConnect);
            server.Start(1988);
            Console.WriteLine("server on:1988");
            while (true)
            {
                Console.ReadLine();
            }
            static async Task on404(HttpContext context)
            {
                await context.Response.WriteAsync("you got a 404");
            }
            static IWebSocketPeer onWebSocketConnect(System.Net.WebSockets.WebSocket websocket)
            {
                return new MyPeer(websocket);
            }

        }
    }
    class MyPeer : IWebSocketPeer
    {
        System.Net.WebSockets.WebSocket websocket;
        public MyPeer(System.Net.WebSockets.WebSocket websocket)
        {
            this.websocket = websocket;
        }
        //接口实现 连接接通回调 
        public async Task OnConnect()
        {
            Console.WriteLine("OnConnect.");
            return;
        }
        //接口实现 连接断开回调
        public async Task OnDisConnect()
        {
            Console.WriteLine("OnDisConnect.");
            return;
        }

        //接口实现 收到信息，websocket 自带分包处理，底层处理了拼包，每次OnRecv一定是一个完整的包
        public async Task OnRecv(MemoryStream stream, int count)
        {
            byte[] buf = new byte[count];
            stream.Read(buf, 0, buf.Length);
            var str = System.Text.Encoding.UTF8.GetString(buf);
            Console.WriteLine("recv:" + str);

            var outbuf = System.Text.Encoding.UTF8.GetBytes("hello world.");
            await SendAsync(outbuf);
        }
        //发送方法
        private async Task SendAsync(byte[] msg)
        {
            await this.websocket.SendAsync(
            msg,//发包 类型为ArraySegment<byte> byte[]的一部分，直接传byte[]会隐式自动转换
            System.Net.WebSockets.WebSocketMessageType.Text,//包类型 二进制还是Text
            //大部分情况无所谓，但js要注意，ws in js，文本会直接收到字符串，不能发非字符，二进制会收到一个blob对象
            true,//是否是结束包，写逻辑没必要专门把一个包分几次发，基本上会一直取true
            CancellationToken.None//Task取消机制，略
            );
        }
    }
}
